package com.travel.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.dto.UserInfoDTO;
import com.travel.enums.OrderStates;
import com.travel.mapper.ScenicSpotMapper;
import com.travel.mapper.UserMapper;
import com.travel.mapper.UserOrderMapper;
import com.travel.pojo.ScenicSpot;
import com.travel.pojo.User;
import com.travel.pojo.UserOrder;
import com.travel.service.UserService;
import com.travel.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @BelongsProject: TravelDream
 * @BelongsPackage: com.travel.service.impl
 * @CreateTime: 2021-05-18 16:18
 * @Description: TODO
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserOrderMapper userOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @Override
    public String saveUserInfo(UserInfoDTO userInfoDTO) {
        // 存入订单表
        UserOrder userOrder = new UserOrder();
        User user = userMapper.selectById(userInfoDTO.getUserId());  // 获取用户身份证号码
        // 设置用户id
        userOrder.setUserId(userInfoDTO.getUserId());
        userOrder.setUserName(userInfoDTO.getName());
        userOrder.setHotelAddress(userInfoDTO.getHotelAddress());
        userOrder.setLinkTel(userInfoDTO.getPhone());  // 设置手机号
        userOrder.setLinkTelBk(userInfoDTO.getBackupContact());  // 设置备用电话
        userOrder.setIcCode(user != null ? user.getIcCode() : ""); // 设置身份证号
        userOrder.setOrderTime(DateUtils.getNowTime());
        userOrder.setSetoffTime(userOrder.getOrderTime());
        // 设置各类型人数
        List<UserInfoDTO.Participant> plist = userInfoDTO.getParticipant();
        int peopleCount = 0;
        for (UserInfoDTO.Participant item : plist) {
            if (item.getLabel().equals("成人")){
                userOrder.setAdultCount(Integer.valueOf(item.getCount()));
                userOrder.setAdultPrice(item.getPrice());
                peopleCount += Integer.parseInt(item.getCount());
            }
            if (item.getLabel().equals("老人学生")){
                userOrder.setOldStuCount(Integer.valueOf(item.getCount()));
                userOrder.setOldStuPrice(item.getPrice());
                peopleCount += Integer.parseInt(item.getCount());
            }
            if (item.getLabel().startsWith("儿童")){
                userOrder.setChildrenCount(Integer.valueOf(item.getCount()));
                userOrder.setChildrenPrice(item.getPrice());
                peopleCount += Integer.parseInt(item.getCount());
            }
        }
        // 设置总人数
        userOrder.setPeopleCount((long) peopleCount);
        // 设置总费用
        userOrder.setFee(userInfoDTO.getTotal());
        // 设置默认状态
        userOrder.setState(OrderStates.TOBESIGN.getName());
        userOrder.setAddTime(DateUtils.getNowTime());  // 设置订单添加时间
        userOrder.setModifyTime(userOrder.getAddTime());  // 设置订单修改时间
        userOrder.setAgentId(userInfoDTO.getAgentId()); // 添加业务员id
        // 插入旅游项目id
        List<String> selectedRoutes = userInfoDTO.getSelectedRoutes();
        String randomId = "";
        if (!selectedRoutes.isEmpty()) {
            Random random = new Random();
            int index = random.nextInt(selectedRoutes.size());
            randomId = selectedRoutes.get(index);
        }
        ScenicSpot scenicSpot = scenicSpotMapper.selectById(randomId);
        if (scenicSpot!=null){
            // 随机保存一个图片到userOrder的imgUrl字段
            userOrder.setImgUrl(scenicSpot.getImgUrl().split(" ")[0]);
        }
        String ids = CollUtil.join(selectedRoutes, ",");
        // 获取产品名称
        List<ScenicSpot> scenicSpots = scenicSpotMapper.selectBatchIds(selectedRoutes);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < scenicSpots.size(); i++) {
            if (i == scenicSpots.size() - 1) {
                stringBuilder.append(scenicSpots.get(i).getSpotName());
                break;
            }
            stringBuilder.append(scenicSpots.get(i).getSpotName() + ";");
        }
        userOrder.setProductName(stringBuilder.toString());

        userOrder.setProductId(ids);
        userOrderMapper.insert(userOrder);
        return userOrder.getId();
    }

    @Override
    public User loginOrRegister(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getLinkTel, phone)
                .eq(User::getDeleteStatus, 0);
        User user = userMapper.selectOne(wrapper);
        // 如果是新用户，则插入
        if (user == null) {
            user = new User();
            user.setLinkTel(phone);
            // 设置默认用户名
            user.setUserName("用户" + phone.substring(phone.length() - 4));
            user.setState(1);
            user.setPassword("123456");
            userMapper.insert(user);
            return userMapper.selectOne(wrapper);
        }
        return user;
    }
}
